import {
  createParamDecorator,
  ExecutionContext,
  SetMetadata,
} from '@nestjs/common';
import { ClassTransformOptions } from 'class-transformer';
import {
  registerDecorator,
  ValidationOptions,
  ValidatorOptions,
  ValidationArguments,
} from 'class-validator';
import * as dayjs from 'dayjs';
import { DTO_VALIDATION_OPTIONS, Paramtype } from 'src/core/constants';

export const RequireLogin = () => SetMetadata('require-login', true);

export const RequirePermission = (...permissions: string[]) =>
  SetMetadata('require-permission', permissions);

// 获取请求数据中的user
export const UserInfo = createParamDecorator(
  (data: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    if (!request.user) {
      return null;
    }
    return data ? request.user[data] : request.user;
  },
);
// 用于配置通过全局验证管道验证数据的DTO类装饰器
export const DtoValidation = (
  options?: ValidatorOptions & {
    transformOptions?: ClassTransformOptions;
  } & { type?: Paramtype },
) => SetMetadata(DTO_VALIDATION_OPTIONS, options ?? {});

//用于校验用户传入的日期格式是否为 YYYY-MM-DD HH:mm:ss
export const IsDayjsFormat = (
  format: string,
  validationOptions?: ValidationOptions,
) => {
  return (object: Record<string, any>, propertyName: string) => {
    registerDecorator({
      name: 'isDayjsFormat',
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      validator: {
        validate(value: any) {
          console.log(value);
          return dayjs(value, format, true).isValid();
        },
        defaultMessage(args: ValidationArguments) {
          return `${args.property}格式错误，应为${format}`;
        },
      },
    });
  };
};
